<template>
	<view class="order-container">
		<!-- 头部标题 -->
		<view class="order-header">
			<view class="header-content">
				<uni-icons type="cart" size="24" color="#FF6EA1"></uni-icons>
				<text class="header-title">我的订单</text>
			</view>
			<view class="header-line"></view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list" v-if="orders.length > 0">
			<view class="order-card" v-for="(item, index) in orders" :key="index">
				<!-- 订单头部 -->
				<view class="card-header">
					<view class="order-info">
						<text class="order-id">订单号: {{item.data[0].order_id}}</text>
						<text class="order-time">{{item.data[0].order_time | dateFormat}}</text>
					</view>
					<view class="order-status">
						<text class="status-tag" :class="getStatusClass(item.data[0].status)">
							{{getStatusText(item.data[0].status)}}
						</text>
						<button class="edit-status-btn" v-if="canEditStatus(item.data[0].status)"
							@click="showStatusDialog(item, index)">
							<uni-icons type="compose" size="16" color="#666"></uni-icons>
							修改状态
						</button>
					</view>
				</view>

				<!-- 收货地址 -->
				<view class="address-section" v-if="item.address">
					<view class="section-title">
						<uni-icons type="location" size="16" color="#999"></uni-icons>
						<text>收货信息</text>
					</view>
					<view class="address-content">
						<view class="address-row">
							<text class="address-label">收件人:</text>
							<text class="address-value">{{item.address.name}}</text>
						</view>
						<view class="address-row">
							<text class="address-label">电话:</text>
							<text class="address-value">{{item.address.phoneNum}}</text>
						</view>
						<view class="address-row">
							<text class="address-label">地址:</text>
							<text class="address-value">{{item.address.content}}</text>
						</view>
					</view>
				</view>

				<!-- 商品列表 -->
				<view class="product-section">
					<view class="section-title">
						<uni-icons type="shop" size="16" color="#999"></uni-icons>
						<text>商品信息</text>
					</view>
					<view class="product-list">
						<view class="product-item" v-for="(product, i) in item.data" :key="i">
							<image class="product-image" :src="'http://localhost:3000/'+product.product_picture"
								mode="aspectFill"></image>
							<view class="product-info">
								<text class="product-name">{{product.product_name}}</text>
								<view class="product-specs">
									<text class="product-price">¥{{product.product_price}}</text>
									<text class="product-num">x{{product.product_num}}</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 订单汇总 -->
				<view class="summary-section">
					<view class="order-summary">
						<text class="total-num">共{{total[index].totalNum}}件商品</text>
						<view class="price-section">
							<text class="total-text">合计:</text>
							<text class="total-price">¥{{total[index].totalPrice}}</text>
						</view>
					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="action-section">
					<button class="action-btn danger" v-if="canCancel(item.data[0].status)"
						@click="cancelOrder(item, index)">
						<uni-icons type="trash" size="16" color="#FF6EA1"></uni-icons>
						取消订单
					</button>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-order" v-else>
			<image class="empty-image" src="/static/empty-order.png" mode="aspectFit"></image>
			<text class="empty-text">您还没有任何订单</text>
			<text class="empty-tip">快去选购心仪的商品吧</text>
			<button class="shopping-btn" @click="goShopping">
				<uni-icons type="arrow-right" size="16" color="#fff"></uni-icons>
				去逛逛
			</button>
		</view>

		<!-- 状态选择弹窗 -->
		<uni-popup ref="statusPopup" type="dialog">
			<uni-popup-dialog mode="base" title="修改订单状态" :content="statusContent" @confirm="confirmStatus"
				@close="closeStatusDialog">
				<picker :range="statusOptions" range-key="label" @change="statusChange">
					<view class="picker">
						当前选择: {{statusOptions[currentStatusIndex].label}}
					</view>
				</picker>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orders: [], // 订单列表
				total: [], // 每个订单的商品数量及总价列表
				currentOrder: null, // 当前操作的订单
				currentOrderIndex: -1,
				statusOptions: [], // 动态生成的状态选项
				currentStatusIndex: 0,
				statusContent: '请选择新的订单状态',
				statusMap: {
					'1': {
						text: '待发货',
						class: 'status-warning',
						editable: true
					},
					'2': {
						text: '已发货',
						class: 'status-info',
						editable: true
					},
					'3': {
						text: '退款中',
						class: 'status-danger',
						editable: false
					},
					'4': {
						text: '已取消',
						class: 'status-default',
						editable: false
					},
					'5': {
						text: '已完成',
						class: 'status-success',
						editable: false
					},
					'6': {
						text: '待付款',
						class: 'status-warning',
						editable: true
					}
				}
			};
		},
		onLoad() {
			this.getOrderList();
		},
		methods: {
			// 获取订单列表
			getOrderList() {
				uni.showLoading({
					title: '加载中...'
				});
				// 这里替换为你的实际API调用
				uni.request({
					url: 'http://localhost:8081/api/user/order/getOrder',
					method: 'POST',
					data: {
						user_id: uni.getStorageSync('user').user_id
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.code === "001") {
							this.orders = res.data.orders.map(order => {
								return {
									...order,
									// 模拟收货地址数据
									address: {
										name: '张三',
										phoneNum: '13800138000',
										content: '北京市朝阳区建国路88号现代城A座1001室'
									}
								}
							});
							this.calculateTotal();
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '请求失败',
							icon: 'none'
						});
						// 模拟数据
						this.mockData();
					}
				});
			},

			// 模拟数据
			mockData() {
				this.orders = [{
						data: [{
								order_id: '20230601123456',
								order_time: '2023-06-01 12:34:56',
								status: '1',
								product_id: '1001',
								product_name: 'JavaScript高级程序设计（第4版）',
								product_picture: '/static/book1.jpg',
								product_price: 99.00,
								product_num: 1
							},
							{
								order_id: '20230601123456',
								order_time: '2023-06-01 12:34:56',
								status: '1',
								product_id: '1002',
								product_name: 'Vue.js设计与实现',
								product_picture: '/static/book2.jpg',
								product_price: 89.00,
								product_num: 2
							}
						],
						address: {
							name: '张三',
							phoneNum: '13800138000',
							content: '北京市朝阳区建国路88号现代城A座1001室'
						}
					},
					{
						data: [{
							order_id: '20230525112233',
							order_time: '2023-05-25 11:22:33',
							status: '2',
							product_id: '1003',
							product_name: 'CSS揭秘',
							product_picture: '/static/book3.jpg',
							product_price: 69.00,
							product_num: 1
						}],
						address: {
							name: '李四',
							phoneNum: '13900139000',
							content: '上海市浦东新区张江高科技园区亮秀路112号'
						}
					}
				];
				this.calculateTotal();
			},

			// 计算订单总价和数量
			calculateTotal() {
				let total = [];
				for (let i = 0; i < this.orders.length; i++) {
					const element = this.orders[i];
					let totalNum = 0;
					let totalPrice = 0;
					for (let j = 0; j < element.data.length; j++) {
						const temp = element.data[j];
						totalNum += temp.product_num;
						totalPrice += temp.product_price * temp.product_num;
					}
					total.push({
						totalNum,
						totalPrice: totalPrice.toFixed(2)
					});
				}
				this.total = total;
			},

			// 获取状态文本
			getStatusText(status) {
				return this.statusMap[status]?.text || '未知状态';
			},

			// 获取状态类名
			getStatusClass(status) {
				return this.statusMap[status]?.class || 'status-default';
			},

			// 是否可以编辑状态
			canEditStatus(status) {
				return this.statusMap[status]?.editable || false;
			},

			// 是否可以取消订单
			canCancel(status) {
				return ['1', '6'].includes(status); // 待发货和待付款可以取消
			},

			// 显示状态选择弹窗
			showStatusDialog(item, index) {
				this.currentOrder = item;
				this.currentOrderIndex = index;
				this.generateStatusOptions(item.data[0].status);
				this.$refs.statusPopup.open();
			},

			// 根据当前状态生成可选项
			generateStatusOptions(currentStatus) {
				const options = [];
				switch (currentStatus) {
					case '1': // 待发货
						options.push({
							label: '已发货',
							value: '2'
						}, {
							label: '取消订单',
							value: '4'
						});
						break;
					case '2': // 已发货
						options.push({
							label: '已完成',
							value: '5'
						}, {
							label: '申请退款',
							value: '3'
						});
						break;
					case '6': // 待付款
						options.push({
							label: '取消订单',
							value: '4'
						});
						break;
				}
				this.statusOptions = options;
				this.currentStatusIndex = 0;
			},

			// 状态选择变化
			statusChange(e) {
				this.currentStatusIndex = e.detail.value;
			},

			// 确认更改状态
			confirmStatus() {
				const newStatus = this.statusOptions[this.currentStatusIndex].value;
				uni.showLoading({
					title: '处理中...'
				});
				// 这里替换为你的实际API调用
				uni.request({
					url: 'http://localhost:8081/api/user/order/changeStatus',
					method: 'POST',
					data: {
						order_id: this.currentOrder.data[0].order_id,
						status: newStatus
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.code === '001') {
							uni.showToast({
								title: '订单状态已更新'
							});
							// 更新本地数据
							this.orders[this.currentOrderIndex].data.forEach(item => {
								item.status = newStatus;
							});
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '请求失败',
							icon: 'none'
						});
					}
				});
			},

			// 关闭状态弹窗
			closeStatusDialog() {
				this.currentOrder = null;
				this.currentOrderIndex = -1;
			},

			// 取消订单
			cancelOrder(item, index) {
				uni.showModal({
					title: '确认取消订单',
					content: '确定要取消这个订单吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							});
							// 这里替换为你的实际API调用
							uni.request({
								url: 'http://localhost:8081/api/user/order/changeStatus',
								method: 'POST',
								data: {
									order_id: item.data[0].order_id,
									status: "3"
								},
								success: (res) => {
									uni.hideLoading();
									if (res.data.code === '001') {
										uni.showToast({
											title: '订单已取消'
										});
										// 更新本地数据
										this.orders[index].data.forEach(item => {
											item.status = '4'; // 已取消
										});
									} else {
										uni.showToast({
											title: res.data.msg,
											icon: 'none'
										});
									}
								},
								fail: (err) => {
									uni.hideLoading();
									uni.showToast({
										title: '请求失败',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			},

			// 查看订单详情
			viewOrderDetail(item) {
				uni.navigateTo({
					url: '/pages/order/detail?id=' + item.data[0].order_id
				});
			},

			// 联系客服
			contactCustomerService(item) {
				uni.makePhoneCall({
					phoneNumber: '4001234567'
				});
			},

			// 去购物
			goShopping() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		},
		filters: {
			// 日期格式化过滤器
			dateFormat(value) {
				if (!value) return '';
				const date = new Date(value);
				const pad = num => num < 10 ? '0' + num : num;
				return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
			}
		}
	};
</script>

<style lang="less" scoped>
	.order-container {
		padding: 20rpx;
		background-color: #f7f7f7;
		min-height: 100vh;
		padding-bottom: 40rpx;
	}

	/* 头部样式 */
	.order-header {
		margin-bottom: 30rpx;
		padding: 20rpx 0;

		.header-content {
			display: flex;
			align-items: center;

			.header-title {
				font-size: 36rpx;
				font-weight: bold;
				margin-left: 15rpx;
				color: #333;
			}
		}

		.header-line {
			width: 80rpx;
			height: 6rpx;
			background: linear-gradient(to right, #FF6EA1, #FF8E9E);
			border-radius: 3rpx;
			margin-top: 15rpx;
		}
	}

	/* 订单卡片 */
	.order-card {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.order-info {
				flex: 1;
				display: flex;
				flex-direction: column;

				.order-id {
					font-size: 26rpx;
					color: #666;
				}

				.order-time {
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
				}
			}

			.order-status {
				display: flex;
				align-items: center;

				.status-tag {
					font-size: 24rpx;
					padding: 6rpx 16rpx;
					border-radius: 20rpx;

					&.status-warning {
						background-color: #FFF6E0;
						color: #FF9500;
					}

					&.status-info {
						background-color: #E8F4FF;
						color: #007AFF;
					}

					&.status-danger {
						background-color: #FFE8E6;
						color: #FF3B30;
					}

					&.status-success {
						background-color: #E6F7E6;
						color: #34C759;
					}

					&.status-default {
						background-color: #F2F2F2;
						color: #666;
					}
				}

				.edit-status-btn {
					margin-left: 20rpx;
					padding: 0 20rpx;
					height: 50rpx;
					line-height: 50rpx;
					font-size: 24rpx;
					color: #666;
					background-color: #fff;
					border: 1rpx solid #ddd;
					border-radius: 25rpx;
					display: flex;
					align-items: center;

					.uni-icons {
						margin-right: 8rpx;
					}
				}
			}
		}

		/* 各部分通用样式 */
		.section-title {
			display: flex;
			align-items: center;
			padding: 20rpx;
			font-size: 28rpx;
			color: #666;
			border-bottom: 1rpx solid #f0f0f0;

			.uni-icons {
				margin-right: 10rpx;
			}
		}

		/* 地址部分 */
		.address-section {
			.address-content {
				padding: 20rpx;

				.address-row {
					display: flex;
					margin-bottom: 10rpx;
					font-size: 26rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.address-label {
						color: #999;
						margin-right: 15rpx;
						width: 80rpx;
					}

					.address-value {
						color: #333;
						flex: 1;
					}
				}
			}
		}

		/* 商品部分 */
		.product-section {
			.product-list {
				.product-item {
					display: flex;
					padding: 20rpx;
					border-bottom: 1rpx solid #f0f0f0;

					&:last-child {
						border-bottom: none;
					}

					.product-image {
						width: 120rpx;
						height: 120rpx;
						border-radius: 8rpx;
						margin-right: 20rpx;
					}

					.product-info {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.product-name {
							font-size: 28rpx;
							color: #333;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							-webkit-box-orient: vertical;
							overflow: hidden;
							text-overflow: ellipsis;
						}

						.product-specs {
							display: flex;
							justify-content: space-between;
							align-items: center;
							margin-top: 15rpx;

							.product-price {
								font-size: 28rpx;
								color: #FF6EA1;
								font-weight: bold;
							}

							.product-num {
								font-size: 24rpx;
								color: #999;
							}
						}
					}
				}
			}
		}

		/* 汇总部分 */
		.summary-section {
			.order-summary {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx;
				border-bottom: 1rpx solid #f0f0f0;

				.total-num {
					font-size: 26rpx;
					color: #666;
				}

				.price-section {
					display: flex;
					align-items: baseline;

					.total-text {
						font-size: 26rpx;
						color: #666;
						margin-right: 10rpx;
					}

					.total-price {
						font-size: 32rpx;
						color: #FF6EA1;
						font-weight: bold;
					}
				}
			}
		}

		/* 操作按钮部分 */
		.action-section {
			display: flex;
			justify-content: flex-end;
			padding: 20rpx;

			.action-btn {
				margin-left: 20rpx;
				padding: 0 30rpx;
				height: 60rpx;
				line-height: 60rpx;
				font-size: 26rpx;
				color: #666;
				background-color: #fff;
				border: 1rpx solid #ddd;
				border-radius: 30rpx;
				display: flex;
				align-items: center;

				.uni-icons {
					margin-right: 8rpx;
				}

				&.primary {
					color: #FF6EA1;
					border-color: #FF6EA1;
				}

				&.danger {
					color: #FF6EA1;
					border-color: #FF6EA1;
				}
			}
		}
	}

	/* 空状态 */
	.empty-order {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 100rpx;

		.empty-image {
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 40rpx;
		}

		.empty-text {
			font-size: 32rpx;
			color: #333;
			margin-bottom: 15rpx;
			font-weight: bold;
		}

		.empty-tip {
			font-size: 26rpx;
			color: #999;
			margin-bottom: 50rpx;
		}

		.shopping-btn {
			background: linear-gradient(to right, #FF6EA1, #FF8E9E);
			color: white;
			padding: 0 80rpx;
			height: 70rpx;
			line-height: 70rpx;
			border-radius: 35rpx;
			font-size: 28rpx;
			box-shadow: 0 8rpx 20rpx rgba(255, 110, 161, 0.3);
			display: flex;
			align-items: center;

			.uni-icons {
				margin-right: 8rpx;
			}
		}
	}

	/* 状态选择器 */
	.picker {
		padding: 20rpx;
		text-align: center;
		color: #FF6EA1;
		font-size: 28rpx;
	}
</style>